// pages/release/auction/auction.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    xianshibaifenbi: false,
    aid: null,
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    userInfo: {},
    searchParams: {
      pageNum: 1,
      pageSize: 6,
      status: '1',
      keyword: '',
      pages: '',
      total: '',
    },
    nocar: true,
    carList: {},
    stepIndex: 1,
    scopeRow: {},
    scopePage: 1,
    scopeIndex: 0,
    publishCar: {
      carId: null,
      loanMoney: '',
      saleMoney: '',
      loanUserName:'',
      loanUserMobile:'',
      loanUserIdCard:'',
      rakeBack:'',
      idCardFrontPic:'',
      idCardBackPic:'',
    },

    placeholderTime: '',
    modalName: null,
    newCar: '',
    optImageType:'',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  doNothing(){},
  onReady: function(){
      this.chooseLogo = this.selectComponent('#chooseLogo');
  },
  onLoad: function (options) {
    this.InitUserStatus();
    // if(options.aid){
    //   this.setData({
    //     'aid':options.aid
    //   });
    //   // 请求拍卖详情信息。
    //   this.loadAuctionMsg();
    // }
    wx.enableAlertBeforeUnload({
        message: "确定要放弃当前填写内容嘛？",
        success: function (res) {
        },
        fail: function (errMsg) {
        },
    });
  },
  
  // 检查一下登录状态。
  async InitUserStatus() {
    app.showLoading("获取用户信息");
    await app.checkToken();
    this.InitUserInfo();
    wx.hideLoading();
  },
  InitUserInfo() {
    let userInfo = app.globalData.userInfo;
    this.setData({
      'userInfo': app.globalData.userInfo
    })
    // 这里再验证一遍权限。
    if (userInfo.roleList.indexOf('manageAuction') == -1) {
      app.showNoAuthOrNoGrant('您无权操作查看此页面');
      return;
    } else {
      // let time = app.formatTime(new Date());
      // this.setData({
      //   'placeholderTime': time,
      //   'publishCar.startTimeType': time + ':00'
      // })
      this.carManageList(this.data.searchParams);
    }
  },
  // 加载拍卖详情。
  // loadAuctionMsg(){
  //   app.sHttp.auctionView(this.data.aid).then(res => {
  //     console.log(res);
  //   }, err => {
  //       app.error(err.msg);
  //   })
  // },

  goQuery() {
    this.setData({
      'searchParams.pageNum': 1,
      'searchParams.total': '',
      'searchParams.pages': '',
      'carList': {}
    });
    this.carManageList(this.data.searchParams);
  },
  carManageList(searchParams) {
    app.sHttp.carManageList(searchParams).then(res => {
      if (searchParams.pageNum == 1 && res.result.carList.length == 0) {
        this.setData({
          'nocar': true
        });
        let self = this;
        wx.showModal({
          title: '提示',
          content: '您的车库还没有车辆，请先发布车辆',
          confirmText:'去发布',
          cancelText:'返回',
          success (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/release/release',
              })
            } else{
              self.BackPage();
            }
          }
        })
      } else {
        let carList = this.data.carList;
        carList[searchParams.pageNum] = res.result.carList;
        this.setData({
          'carList': carList,
          'nocar': false,
          'searchParams.pages': res.result.pages,
          'searchParams.total': res.result.total
        })
      }
    }, err => {
      app.error(err.msg);
    })
  },
  nextStep() {
    if (Object.keys(this.data.scopeRow).length === 0) {
      app.alert('请选择车辆');
      return;
    }
    if(0 == this.data.publishCar.rakeBack){
      app.alert('请输入展厅服务费比例');
      return;
    }
    let self = this;
    this.setData({
      'stepIndex': 2,
      'publishCar.carId': self.data.scopeRow.carId
    })
  },
  isHaveAuth(authIcon){
    let index = this.data.userInfo.roleList.indexOf(authIcon);
    return index != -1?true:false;
  },
  backStep() {
    this.setData({
      publishCar: {
        carId: null,
        loanMoney: '',
        saleMoney: '',
        loanUserName:'',
        loanUserMobile:'',
        loanUserIdCard:'',
        rakeBack:'',
        idCardFrontPic:'',
        idCardBackPic:'',
      },
      canSub: false,
      stepIndex: 1
    })
  },
  BackPage() {
    var that = this;
    wx.navigateBack({
      delta: 1,
      fail: function () {
        that.toHome();
      }
    });
  },
  toHome() {
    wx.disableAlertBeforeUnload({
        success: function (res) {
        },
        fail: function (errMsg) {
        },
    });
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  bindtapInput(e) {
    this.setData({
      'searchParams.keyword': e.detail.value
    })
  },
  onReachBottom() {
    if (this.data.searchParams.pageNum == this.data.searchParams.pages) {
      //app.alert('没有更多了哦~');
    } else {
      let self = this;
      this.setData({
        'searchParams.pageNum': self.data.searchParams.pageNum + 1
      });
      this.carManageList(this.data.searchParams);
    }
  },
  chooseCar(e) {
    let page = e.currentTarget.dataset.page;
    let index = e.currentTarget.dataset.idx;
    let item = this.data.carList[page][index];
    this.setData({
      'scopeRow': item,
      'scopePage': page,
      'scopeIndex': index
    })
  },
  publishCarInput(e) {
    let publishCar = this.data.publishCar;
    publishCar[e.currentTarget.dataset.name] = e.detail.value;
    this.setData({
      'publishCar': publishCar
    });
    this.validSubParams();
  },
  validSubParams() {
    let yuan = {
      carId: null,
      loanMoney: '',
      saleMoney: '',
      loanUserName:'',
      loanUserMobile:'',
      loanUserIdCard:'',
      rakeBack:'',
      idCardFrontPic:'',
      idCardBackPic:'',
    };
    let publishCar = this.data.publishCar;
    let canSub = true;
    for (const key in publishCar) {
      if (Object.hasOwnProperty.call(publishCar, key) && Object.hasOwnProperty.call(yuan, key)) {
        if ('picList' != key) {
          if (yuan[key] == publishCar[key]) {
            canSub = false;
          }
        }

      }
    };
    this.setData({
      'canSub': canSub
    });
    return canSub;
  },
  /**
   * 日历控件绑定函数 
   * 点击日期返回
   */
  // onPickerChange: function (e) {
  //   this.setData({
  //     'publishCar.startTimeType': e.detail.dateString + ':00'
  //   })
  // },
  showModal(e) {
    if('typeChoose' == e.currentTarget.dataset.target){
      this.setData({
        'optImageType': e.currentTarget.dataset.type
      })
    }
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  changeIcon(e) {
    let name = e.currentTarget.dataset.name;
    let item = e.currentTarget.dataset.item;
    let publishCar = this.data.publishCar;
    publishCar[name] = item;
    this.setData({
      'publishCar': publishCar
    });
    this.validSubParams();
  },
  submitCar() {
    if (this.validSubParams()) {
      let self = this;
      let publishCar = app.deepCopy(self.data.publishCar);
      publishCar.carId = self.data.scopeRow.carId;
      app.sHttp.custMagerCarLoanClueAdd(publishCar).then(res => {
        let _that = this;
        wx.showModal({
            title: '提交完成',
            content: '您的业务提交完成',
            confirmText:'我知道了',
            showCancel: false,
            success (res) {
              _that.BackPage();
            }
          })
    },err =>{
      app.error(err.msg||err);
    })
    }else{
      app.alert('请填写完整信息后发布');
  }
  },
  seeNewCar(){
    wx.disableAlertBeforeUnload({
        success: function (res) {
        },
        fail: function (errMsg) {
        },
    });
      wx.redirectTo({
        url: '/pages/me/auction/auction',
      })
  },
  // 服务费
  fuwufeijiaodian(){
    this.setData({
      'xianshibaifenbi': true
    })
  },
  lost_fuwufeijiaodian(){
    this.setData({
      'xianshibaifenbi': false
    })
  },
  
  ChooseImageByxiangji() {
    this.hideModal();
    let self = this;
    wx.chooseImage({
      count: 1, //默认1
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'],
      success: (res) => {
        console.log('微信回调',res);
        if('idCardFrontPic' == this.data.optImageType){
          this.setData({
            'publishCar.idCardFrontPic': res.tempFilePaths[0]
          })
          this.uploadTheImage();
        }else if('idCardBackPic' == this.data.optImageType){
          this.setData({
            'publishCar.idCardBackPic': res.tempFilePaths[0]
          })
          this.uploadTheImage();
        }
      }
    });
  },
  ChooseImageByxiangce() {
    this.hideModal();
    let self = this;
    wx.chooseImage({
      count: 1, //默认1
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'],
      success: (res) => {
        console.log('微信回调',res);
        if('idCardFrontPic' == this.data.optImageType){
          this.setData({
            'publishCar.idCardFrontPic': res.tempFilePaths[0]
          })
          this.uploadTheImage();
        }else if('idCardBackPic' == this.data.optImageType){
          this.setData({
            'publishCar.idCardBackPic': res.tempFilePaths[0]
          })
          this.uploadTheImage();
        }
      }
    });
  },
  ChooseImage() {
    this.hideModal();
    let self = this;
    wx.chooseImage({
      count: 1, //默认1
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album','camera'],
      success: (res) => {
        console.log('微信回调',res);
        if('idCardFrontPic' == this.data.optImageType){
          this.setData({
            'publishCar.idCardFrontPic': res.tempFilePaths[0]
          })
          this.uploadTheImage();
        }else if('idCardBackPic' == this.data.optImageType){
          this.setData({
            'publishCar.idCardBackPic': res.tempFilePaths[0]
          })
          this.uploadTheImage();
        }
      }
    });
  },
  chooseMessageFile(){
    this.hideModal();
    let self = this;
    wx.chooseMessageFile({
      count: 1, //默认1
      type: 'image',
      success: (res) => {
        console.log('微信回调',res);
        res.tempFilePaths = [];
        res.tempFiles.forEach(item =>{
          res.tempFilePaths.push(item.path);
        })
        if('idCardFrontPic' == this.data.optImageType){
          this.setData({
            'publishCar.idCardFrontPic': res.tempFilePaths[0]
          })
          this.uploadTheImage();
        }else if('idCardBackPic' == this.data.optImageType){
          this.setData({
            'publishCar.idCardBackPic': res.tempFilePaths[0]
          })
          this.uploadTheImage();
        }
      }
    });
  },
  
  async uploadTheImage(){
    let idCardFrontPic = "";
    if('idCardFrontPic' == this.data.optImageType){
      idCardFrontPic = this.data.publishCar.idCardFrontPic;
    }else if('idCardBackPic' == this.data.optImageType){
      idCardFrontPic = this.data.publishCar.idCardBackPic;
    }
    if (idCardFrontPic.indexOf('tmp') != -1 || idCardFrontPic.indexOf('wxfile') != -1) {
      // 压缩一下再上传
      if(idCardFrontPic.substring(idCardFrontPic.length-3) == 'jpg'){
        const compressImage = app.promisify(wx.compressImage);
        console.log(idCardFrontPic);
        const res = await compressImage({
          src: idCardFrontPic, // 图片路径
          quality: 67 // 压缩质量
        });
        idCardFrontPic = res.tempFilePath;
      } 
      let self = this;
      app.sHttp.upload({'filePath':idCardFrontPic,'fileType':'dealerData','isNeedThumbnail':0}).then(res=>{
        if('idCardFrontPic' == self.data.optImageType){
          self.setData({
            'publishCar.idCardFrontPic': res.originalUrl
          });
          // 进行识别。
          self.ocrDiscern();
        }else if('idCardBackPic' == self.data.optImageType){
          self.setData({
            'publishCar.idCardBackPic': res.originalUrl
          });
        }
        self.validSubParams()
      },err=>{
        app.error(err.msg);
      })
    }
  },    // OCR识别数据
  ocrDiscern(){
      app.sHttp.ocrDiscern({cardType:4,imageUrl:this.data.publishCar.idCardFrontPic}).then(res =>{
        if(res.result.idCard){
          this.setData({
            'publishCar.loanUserIdCard': res.result.idCard,
            'publishCar.loanUserName': res.result.userName
          });
        }else{
          app.alert('识别失败请重试');
          this.setData({
            'publishCar.idCardFrontPic': ''
          });
        }
        this.validSubParams();
      },err=>{
          app.error(err.msg);
      })
  },
})